//
//  ViewController.m
//  ImageGif
//
//  Created by Agensn on 2017/3/29.
//  Copyright © 2017年 🌹Agensn_Master🌹. All rights reserved.
//

#import "ViewController.h"

#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    //1.获取GIF数据
    NSString *path = [[NSBundle mainBundle]pathForResource:@"ColorfulTabBarDesign" ofType:@"gif"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    //获取
    CGImageSourceRef gifRef = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    //2.一共有多少帧
    size_t gifCount = CGImageSourceGetCount(gifRef);
    NSLog(@"%zu",gifCount);
    
    NSMutableArray *imgArr = [NSMutableArray array];
    for (size_t i = 0; i < gifCount; i++) {
        //获取单帧数据
        CGImageRef imgRef = CGImageSourceCreateImageAtIndex(gifRef, i, NULL);
        //将单帧数据转换为jpg                       //传入            大小              取向(方向)
        UIImage *jpgImg = [UIImage imageWithCGImage:imgRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
        //添加到数组
        [imgArr addObject:jpgImg];
        //释放
        CGImageRelease(imgRef);
    }
    //释放
    CFRelease(gifRef);
    
    //单帧图片保存到相册
    int i = 0;    //图片名称
    for (UIImage *image in imgArr) {
        //转换为png
        NSData *pngImg = UIImagePNGRepresentation(image);
//        NSData *jpgImg = UIImageJPEGRepresentation(image, 0.5);  //后面参数为改变清晰度
        //返回一个绝对路径
        NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *imagePath = path[0];
        NSString *imgNum = [imagePath stringByAppendingString:[NSString stringWithFormat:@"%d,png",i]];
        i++;
        
        [pngImg writeToFile:imgNum atomically:NO];
        
        //将图片保存到相册
        UIImage *img = [UIImage imageWithData:pngImg];
        UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
